HTML5 introduces a new HTML element: the CANVAS tag. This tag allows for two dimensional drawing easily using Javascript. This makes it perfect for producing graphs. You've already seen how to draw basic shaps in my previous tutorial Drawing on the Canvas, but drawing something complex requires a lot more JavaScript. We need a graphing library to help us along.
RGraph is a HTML5 canvas graph library based on the canvas tag. Like most graph library, RGraph support wide variety of graph types including bar chart, pie chart, radar chart, etc.
It ridiculously simple to draw graphs using the HTML5 canvas. It's a pure JavaScript solution, though, so it won't work for those user agents that don't have JavaScript available, but then again, neither will the canvas.
Here's the code for a very simple bar graph:
Download the Rgraph html 5.0 canvas libraries, and place the files in libraries folder into the 'js' folder.
We're using bar graph, so we need both the RGraph Bar graph library and ' the core RGraph library. We'll also use jQuery to grab the data out of the document. In the head section of the HTML page, we need to load the libraries we need.
Full Code
Output
This will be your fallback content for mobile devices and other users where either the canvas element or JavaScript is not available.
We use that same logic again on line 8 to grab an array of the percentages.
We simply leave the data outside the canvas and then hide it with jQuery once we'€™ve checked that the canvas exists.
Full Code
Now that you know a little about how the canvas works, you can start thinking of other ways you might use it. You could use it to create a game, create a user interface for a media player, or use it to build a better image gallery. All you need to start painting is a little bit of JavaScript and a little bit of imagination.